import sys
import getopt
class Stats:

    def __init__(self, filename):
        self.lst = []
        self._outLst = []
        self.qps = dict()
        self._load_list(filename)
        self.Save(filename)

    def _load_list(self,filename):
        all_lines = self._get_file(filename)

        for x in range(len(all_lines)):
            self.lst.append(all_lines[x].split('\t'))

        for line in self.lst:            
            key = line[1]
            keys = self.qps.keys()
            if key in keys:
                self.qps[key] += 1
            else:
                if key != "seconds":
                    self.qps[key] = 1

    def _get_file(self,filename):
            file_object = open(filename)
            try:
                return file_object.read().splitlines()
            finally:
                file_object.close()

    def Save(self,filename):
        """ Save whole network to file """        
        self._outLst = []
        self._net2file(self.qps)
        self._save(filename)

    def _net2file(self, dic):
        for key, value in dic.items():
            self._outLst.append("%s    %s\n" %(key, value))

    def _save(self,filename):
        """ Save file """
        try:
            fout = open('%s_qps.txt'%filename, 'w')

            try:
                for line in self._outLst:
                    fout.write(line)
            finally:
                fout.close()
        except IOError:
            pass

if __name__ == "__main__":
    try: 
        opts, args = getopt.getopt(sys.argv[1:], "f:", ["filename="])
    except getopt.GetoptError:
        print "CLI args parsing error"
        sys.exit(2)

    for opt, arg in opts:
        if opt in ("-f", "--filename"):
            filename = arg
    Stats(filename)
